package client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.security.KeyStore;
import java.util.Scanner;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class ClientConnection {
	private static String password;

	public static void main(String[] args) throws Exception {
		String host = "localHost";
		int port = 4000;
		try {

			/*
			 * Set up a key manager for client authentication if asked by the
			 * server. Use the implementation's default TrustStore and
			 * secureRandom routines.
			 */
			SSLSocketFactory factory = null;
			try {
				SSLContext ctx;
				KeyManagerFactory kmf;
				TrustManagerFactory tmf;
				KeyStore ts;
				KeyStore ks;
				char[] passphrase = "password".toCharArray();

				ts = KeyStore.getInstance("JKS");
				System.out.println("Enter username");
				Scanner scam = new Scanner(System.in);
				String username = scam.nextLine();
				System.out.println("Enter password");
				password = scam.nextLine();
				ts.load(new FileInputStream("cert script/test/" + username
						+ ".jks"), passphrase);
				tmf = TrustManagerFactory.getInstance("SunX509");
				tmf.init(ts);

				ctx = SSLContext.getInstance("SSL");
				kmf = KeyManagerFactory.getInstance("SunX509");
				ks = KeyStore.getInstance("JKS");

				ks.load(new FileInputStream("cert script/test/" + username
						+ ".jks"), passphrase);

				kmf.init(ks, passphrase);
				System.out.println(ks.getCertificateAlias(ts
						.getCertificate("root")));
				System.out
						.println(((X509TrustManager) tmf.getTrustManagers()[0])
								.getAcceptedIssuers()[0].getSubjectDN()
								.getName());
				ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

				factory = ctx.getSocketFactory();
			} catch (Exception e) {
				throw new IOException(e.getMessage());
			}

			SSLSocket socket = (SSLSocket) factory.createSocket(host, port);

			/*
			 * send http request
			 * 
			 * See SSLSocketClient.java for more information about why there is
			 * a forced handshake here when using PrintWriters.
			 */
			socket.startHandshake(); // acknowledge accept call and verifies
										// certificate

			PrintWriter out = new PrintWriter(new BufferedWriter(
					new OutputStreamWriter(socket.getOutputStream())));

			/*
			 * Make sure there were no surprises
			 */
			if (out.checkError())
				System.out
						.println("SSLSocketClient: java.io.PrintWriter error");

			/* read challenge and send response */
			BufferedReader in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			String ch = in.readLine();
			out.println(processCh(ch));
			out.flush();
			new Terminal(out, in);

			in.close();
			out.close();
			socket.close();

		} catch (Exception e) {
			System.out.println("An error, program exit");
		}
	}

	/* Do secret stuff with the challenge */
	private static String processCh(String ch) {
		char[] firstNFinal = password.toCharArray();
		if (firstNFinal.length != 8) {
			return ch;
		}
		String append = firstNFinal[0] + ""
				+ firstNFinal[firstNFinal.length - 1];
		String response = (ch + append);
		return response;
	}

}
